package com.boot.dog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.dog.common.constant.SecurityConst;
import com.boot.dog.common.enums.ButtonType;
import com.boot.dog.common.enums.UserType;
import com.boot.dog.common.util.ApiResult;
import com.boot.dog.common.util.Result;
import com.boot.dog.entities.base.BasePojo;
import com.boot.dog.entities.pojo.Permission;
import com.boot.dog.entities.pojo.Role;
import com.boot.dog.entities.pojo.User;
import com.boot.dog.mapper.PermissionMapper;
import com.boot.dog.service.PermissionService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Service
@AllArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final PermissionMapper permissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Void> savePermission(Permission permission) {
        if (SecurityConst.PERMISSION_OPERATION.equals(permission.getType())) {
            Integer count = permissionMapper.selectCount(Wrappers.<Permission>query().lambda().eq(Permission::getTitle, permission.getTitle()));
            if (count > 0) {
                return Result.warn("按钮名称已存在");
            }
            permission.setIcon(ButtonType.getIcon(permission.getButtonType()));
        }
        permissionMapper.insert(permission);
        return Result.ok("添加权限成功");
    }

    @Override
    public ApiResult<List<Permission>> searchPermissions(String title) {
        List<Permission> permissions = permissionMapper.selectList(Wrappers.<Permission>query().lambda().like(Permission::getTitle, title));
        return Result.of(permissions);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Void> delById(Integer id) {
        Integer childCount = permissionMapper.selectCount(Wrappers.<Permission>query().lambda().eq(Permission::getParentId, id));
        if (childCount > 0) {
            return Result.warn("存在子权限，无法删除");
        }
        Integer roleCount = permissionMapper.selectRoleCount(id);
        if (roleCount > 0) {
            return Result.warn("权限下存在角色，无法删除");
        }
        permissionMapper.deleteById(id);
        return Result.ok("删除权限成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Void> editPermission(Permission permission) {
        if (SecurityConst.PERMISSION_OPERATION.equals(permission.getType())) {
            Integer count = permissionMapper.selectCount(Wrappers.<Permission>query().lambda().ne(Permission::getTitle, permission.getTitle()));
            if (count > 0) {
                return Result.warn("按钮名称已存在");
            }
            permission.setIcon(ButtonType.getIcon(permission.getButtonType()));
        }
        if (permission.getStatus().equals(SecurityConst.PERMISSION_STATUS_DISABLE)) {
            Integer childCount = permissionMapper.selectCount(Wrappers.<Permission>query().lambda().eq(Permission::getParentId, permission.getId()).eq(Permission::getStatus, SecurityConst.PERMISSION_STATUS_NORMAL));
            if (childCount > 0) {
                return Result.warn("子权限存在启用状态，无法禁用父权限");
            }
        }
        permissionMapper.updateById(permission);
        return Result.ok("编辑权限成功");
    }

    @Override
    public List<Permission> findByParentIdOrderBySortOrder(Integer parentId) {
        return permissionMapper.selectList(Wrappers.<Permission>query().lambda().eq(Permission::getParentId, parentId).orderByAsc(Permission::getSortOrder));
    }

    @Override
    public List<Permission> findByLevelOrderBySortOrder(Integer level) {
        return permissionMapper.selectList(Wrappers.<Permission>query().lambda().eq(Permission::getLevel, level).orderByAsc(Permission::getSortOrder));
    }

    @Override
    public List<Permission> findCurrByLevelOrderBySortOrder(Integer level, User user) {
        if (StrUtil.equals(UserType.SUPER_ADMIN.code(), user.getUserType())) {
            return permissionMapper.selectList(Wrappers.<Permission>query().lambda().eq(Permission::getLevel, level).orderByAsc(Permission::getSortOrder));
        }
        return permissionMapper.selectByRoleIdsAndLevelAndDistinct(user.getRoles().stream().map(Role::getId).collect(Collectors.toList()), level);
    }

    @Override
    public List<Permission> findCurrByParentIdOrderBySortOrder(Integer parentId, User user) {
        if (StrUtil.equals(UserType.SUPER_ADMIN.code(), user.getUserType())) {
            return permissionMapper.selectList(Wrappers.<Permission>query().lambda().eq(Permission::getParentId, parentId).orderByAsc(Permission::getSortOrder));
        }
        return permissionMapper.selectByRoleIdsAndParentIdAndDistinct(user.getRoles().stream().map(Role::getId).collect(Collectors.toList()), parentId);
    }
}
